package com.etl.extract;

import com.etl.task.basic.ITask;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2020-10-21 10:22
 */
@Slf4j
@Component
public class TaskBuilder {

    /**
     * 应用上下文
     */
    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 任务Bean键值对
     */
    private Map<String, ITask> taskBeanMap;

    /**
     * 任务BeanMap初始化
     */
    @PostConstruct
    public void init() {
        taskBeanMap = applicationContext.getBeansOfType(ITask.class);
    }

    /**
     * 根据任务编码获取任务Bean
     *
     * @param taskCode 任务编码
     * @return Optional
     */
    public Optional<ITask> getTask(String taskCode) {
        if (MapUtils.isEmpty(taskBeanMap) || Objects.isNull(taskCode)) {
            log.error("The ITask Bean Map is empty or taskCode is null");
            return Optional.empty();
        }
        return Optional.ofNullable(taskBeanMap.get(taskCode));
    }
}
